<?php
/**
 *
 * User: chenjunliang@star-net.cn
 * Time: 2017/11/23 17:19
 */

namespace kmsign;


use think\Config;

class baidusign {

    /**
     * 返回签名md5字符串
     * @param  array $arrParam 签名参数数组
     * @param string $signName 签名字段
     * @return string
     */
    public static function getSignStr($arrInput, $arrAuth) {

        $appsecret         = $arrAuth['appsecret'];
        $appid             = $arrAuth['app_id'];
        $arrInput['app_id'] = $appid;
        $strTrans          = '';
        if(isset($arrInput['sign'])) {
            unset($arrInput['sign']);
        }
        // 按key值升序排序
        if(ksort($arrInput)) {
            foreach($arrInput as $key => $value) {
                $strVal = trim($value);
                //判断是否是json数据
                if(is_numeric($strVal) || is_string($strVal)) {
                    $strTrans .= '&'.$key .'='. $strVal;
                } else {
                    $strTrans .= '&'.$key .'=';
                }
            }
            $strSign = md5($appsecret.$strTrans);
        }

        return strtolower($strSign);

    }

    /**
     * 验证签名是否正确
     * @param array $arrParam 签名参数数组
     * @param string $signName 签名字段
     * @return bool
     */
    public static function checkSign($arrInput, $signName = 'auth') {
        $arrAuth = Config::get($signName);
        if(!isset($arrInput['sign'])) {
            return false;
        }

        return self::getSignStr($arrInput, $arrAuth) == $arrInput['sign'];
    }
}